package nl.janvanloenen.bkc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import nl.janvanloenen.bkc.Match.State;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class http {

	private String baseurl = "http://janvanloenen.nl/";
	private List<Match> matches;
	private DatabaseHandler db;
	private String returnString;

	/*
	 * Get all data from the server Add to local database one-by-one
	 */
	public Match[] getAllFromServer() {
		// TODO: Internet connection message
		// isNetworkAvailable(null);

		// get array from server
		JSONArray jarray = getJSONArrayFromServer();
		Match matches[] = new Match[jarray.length()];

		// add to database
		if (jarray != null) {
			for (int i = 0; i < jarray.length(); i++) {
				try {
					JSONObject jObject = jarray.getJSONObject(i);
					matches[i] = decodeJSON(jObject);
				} catch (JSONException e) {
					System.out.println("JSONException GetAllFromServer");
					// e.printStackTrace();
				}

			}
			return matches;
		}
		return null;
	}

	/*
	 * Get JSONArray from server
	 */
	public JSONArray getJSONArrayFromServer() {
		JSONArray returnArray = null;
		String url = baseurl + "bkc/getAll.php";

		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
					returnString = builder.toString(); // + "\n";
				}
				if (returnString.equals(null)) {
				} else if (returnString.equals("")) {
				} else if (returnString.equals("null")) {
				} else if (returnString.equals("\n")) {
				} else if (returnString.equals("null\n")) {
				} else {
					try {
						returnArray = new JSONArray(returnString);
						// System.out.println(returnArray);
					} catch (JSONException e) {
						System.out.println("Hier is de Exception");
						System.out.print(returnString);
						e.printStackTrace();
					}
				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
		return returnArray;
	}

	// decode from JSON to MATCH
	public Match decodeJSON(JSONObject json) {
		Match m = new Match();
		try {
			m.setID(Integer.parseInt(json.getString("id").toString()));
			m.setTeamA(json.getString("team_a").toString());
			m.setTeamB(json.getString("team_b").toString());
			m.setDate(json.getString("date").toString());
			m.setStartTime(Long.parseLong(json.getString("start_time")
					.toString()));
			m.setEndTime(Long.parseLong(json.getString("end_time").toString()));
			m.setScoreTeamA(Integer.parseInt(json.getString("scoreteama")
					.toString()));
			m.setScoreTeamB(Integer.parseInt(json.getString("scoreteamb")
					.toString()));
			m.setState(State.UPTODATE);
			return m;
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	// TODO: insert to server

	// TODO: update to server

	// Encode to JSON
	public JSONArray encodeJSON(List<Match> matches) {
		//List<Match> matches = db.getAllMatches();
		JSONArray jsonArray = new JSONArray();
		try {
			for (Match match : matches) {
				JSONObject obj =  new JSONObject();
				obj.put("team_a", match.getTeamA());
				obj.put("team_b", match.getTeamB());
				obj.put("date", match.getTeamA());
				obj.put("start_time", match.getTeamA());
				obj.put("end_time", match.getTeamA());
				obj.put("scoreteama", match.getTeamA());
				obj.put("scoreteamb", match.getTeamA());
				
				jsonArray.put(obj);
			}
			return jsonArray;
		} catch (Exception e) {
			System.out.println("encodeJSON Failed!");
			return null;
		}
	}

	// Insert to DB
	public void insertIntoDb() {
		for (Match m : matches) {
			db.addMatch(m);
		}
	}

	// Update to DB
	public void updateIndb() {
		for (Match m : matches) {
			db.updateMatch(m);
		}
	}

	/* Check For Network availabilities */
	public static boolean isNetworkAvailable(Context context) {
		// boolean isNetworkAvailable = false;
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						// isNetworkAvailable = true;
						return true;
					}
				}
			}
		}
		return false;
	}
}
